import { useState } from "react";
// import type { BugReport } from "../types/bug";
import { UI_STRINGS } from "../config/strings";
import { STYLES } from "../config/styles";

import type { BugReport } from "../types/bug";

interface Props {
  report: BugReport | null;
  onFixIssue?: (issue: { file: string; line?: number; message?: string }) => void;
  fixing?: boolean;
  onValidateReport?: () => void;
  validating?: boolean;
  scanCompleted?: boolean;
}

export function ReportView({ report, onFixIssue, fixing, onValidateReport, validating, scanCompleted }: Props) {
  const [showSkipped, setShowSkipped] = useState(false);
  
  if (!report) return null;

  // 按文件分组
  const fileMap = new Map<string, typeof report.issues>();
  report.issues.forEach((issue) => {
    const list = fileMap.get(issue.file) || [];
    list.push(issue);
    fileMap.set(issue.file, list);
  });

  const totalIssues = report.issues.length;
  const filesWithIssues = fileMap.size;
  const skippedCount = report.meta?.skipped?.length || 0;


  return (
    <div className="mt-6">
      <h2 className="text-lg font-semibold mb-3">{UI_STRINGS.reportTitle}</h2>

      {/* 汇总统计 */}
      <div className="mb-4 p-3 bg-blue-50 border border-blue-200 rounded-lg flex gap-6 text-sm">
        <div>
          <span className="font-semibold text-gray-700">检测文件：</span>
          <span className="text-blue-700">{filesWithIssues} 个</span>
        </div>
        <div>
          <span className="font-semibold text-gray-700">发现问题：</span>
          <span className="text-orange-600">{totalIssues} 个</span>
        </div>
        <div>
          <span className="font-semibold text-gray-700">跳过文件：</span>
          <span className="text-gray-600">{skippedCount} 个</span>
        </div>
      </div>

      {/* 无问题提示 */}
      {totalIssues === 0 && (
        <div className="p-4 bg-green-50 border border-green-200 rounded-lg text-green-700">
          ✅ 未发现代码问题，干得漂亮！
        </div>
      )}

      {/* 按文件展示问题 */}
      {Array.from(fileMap.entries()).map(([file, issues]) => (
        <div key={file} className="mb-4 border border-gray-200 rounded-lg overflow-hidden">
          <div className="bg-gray-100 px-4 py-2 font-mono text-sm flex items-center justify-between">
            <span className="font-semibold text-gray-800">📄 {file}</span>
            <span className="text-xs bg-orange-100 text-orange-700 px-2 py-1 rounded">
              {issues.length} 个问题
            </span>
          </div>
          <div className="divide-y divide-gray-100">
            {issues.map((issue, idx) => (
              <div key={idx} className="p-3 hover:bg-gray-50">
                <div className="flex items-start gap-3">
                  <span className="text-orange-500 text-lg">⚠️</span>
                  <div className="flex-1">
                    <div className="flex items-center gap-2 mb-1">
                      {issue.line && (
                        <span className="text-xs bg-gray-200 text-gray-700 px-2 py-0.5 rounded font-mono">
                          L{issue.line}
                        </span>
                      )}
                      <span className="text-sm font-medium text-gray-800">
                        {issue.message}
                      </span>
                    </div>
                    {issue.suggestion && (
                      <div className="text-xs text-gray-600 mt-1">
                        💡 {issue.suggestion}
                      </div>
                    )}
                  </div>
                  {onFixIssue && (
                    <button
                      className={STYLES.btnSecondary}
                      disabled={!!fixing}
                      onClick={() => onFixIssue({ file: issue.file, line: issue.line, message: issue.message })}
                      title="仅修复此问题"
                    >
                      {fixing ? UI_STRINGS.fixing : UI_STRINGS.fixThisIssue}
                    </button>
                  )}
                </div>
              </div>
            ))}
          </div>
        </div>
      ))}

      {/* 生成检验报告按钮（放在检测结果之后，且仅在检测完成后显示） */}
      {onValidateReport && scanCompleted && (
        <button
          className={STYLES.btnPrimary + " mb-4"}
          disabled={!!validating}
          onClick={onValidateReport}
        >
          {validating ? "正在生成并下载检验报告..." : "生成并下载检验报告"}
        </button>
      )}

      {/* 跳过文件列表（可折叠） */}
      {skippedCount > 0 && (
        <div className="mt-4 border border-gray-200 rounded-lg overflow-hidden">
          <button
            onClick={() => setShowSkipped(!showSkipped)}
            className="w-full bg-gray-700 px-4 py-2 text-sm font-medium text-white hover:bg-gray-600 flex items-center justify-between"
          >
            <span>🚫 跳过的文件 ({skippedCount})</span>
            <span>{showSkipped ? "▲" : "▼"}</span>
          </button>
          {showSkipped && (
            <div className="p-3 bg-gray-800 max-h-40 overflow-y-auto">
              <ul className="text-xs text-white space-y-1">
                {report.meta?.skipped?.map((name, i) => (
                  <li key={i} className="truncate">
                    • {name}
                  </li>
                ))}
              </ul>
            </div>
          )}
        </div>
      )}
    </div>
  );
}
